package commRedisList

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedis"
	"time"
)

type RedisValueService struct {
	Timeout int64
}

func (e *RedisValueService) PHSet(prefixKey string, hashKey string, value string) error {
	mainKey := prefixKey + ":" + hashKey
	_, err := commRedis.Client.Set(mainKey, value, time.Duration(e.Timeout)*time.Millisecond).Result()
	if err != nil {
		return err
	}

	return nil
}

func (e *RedisValueService) PHGet(prefixKey string, hashKey string, timeout time.Duration) (string, error) {
	mainKey := prefixKey + ":" + hashKey
	return e.GetValue(mainKey, timeout)
}

func (e *RedisValueService) GetValue(mainKey string, timeout time.Duration) (string, error) {
	start := time.Now().UnixMilli()
	for true {
		str, _ := commRedis.Client.Get(mainKey).Result()

		if str != "" {
			_, err := e.expire(mainKey, 0)
			if err != nil {
				return "", err
			}
			return str, nil
		}

		if time.Now().UnixMilli()-start > timeout.Milliseconds() {
			return "", nil
		}
	}

	return "", nil
}

func (e *RedisValueService) expire(mainKey string, timeout int64) (bool, error) {
	return commRedis.Client.Expire(mainKey, time.Duration(timeout)*time.Millisecond).Result()
}
